package middleware

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"io"
	"time"
)

// LoggerMiddleware 自定义日志中间件
func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		var bodyStr string
		if c.Request.Body != nil {
			contentType := c.GetHeader("Content-Type")
			if contentType == "application/octet-stream" || contentType == "multipart/form-data" {
				bodyStr = "[file upload]"
			} else {
				body, _ := io.ReadAll(c.Request.Body)
				c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
				bodyStr = string(body)
			}
		}

		c.Next()

		latency := time.Since(start)

		zap.S().Infof(
			"| %3d | %13v | %-7s %s | IP: %s | UA: %s | \n Body: %s",
			c.Writer.Status(),
			latency,
			c.Request.Method,
			c.Request.URL.Path,
			c.ClientIP(),
			c.Request.UserAgent(),
			bodyStr,
		)
	}
}
